package com.hsnn.medstgmini.trading.catalog.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.dict.model.form.DicAreaForm;
import com.hsnn.medstgmini.base.dict.service.DicAreaManager;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.base.std.service.StdHospInfoManager;
import com.hsnn.medstgmini.pro.project.service.BidProjproddrugManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.sys.model.UserType;
import com.hsnn.medstgmini.trading.catalog.model.SubGoods;
import com.hsnn.medstgmini.trading.catalog.model.SubHospInfo;
import com.hsnn.medstgmini.trading.catalog.model.form.GoodsSelectForm;
import com.hsnn.medstgmini.trading.catalog.service.HospCatalogManager;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.DicSysUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 医院商品目录查看
 * @author 蔡春龙
 * @date 2015年6月14日
 */
@Controller
@RequestMapping("/hospCatalog")
public class HospCatalogController {

	private static final Logger log = Logger.getLogger(HospCatalogController.class);

	@Autowired
	private HospCatalogManager hospCatalogManager;

	@Autowired
	private StdHospInfoManager hospInfoManager;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private DicAreaManager dicAreaManager;
	
	@Autowired
	private BidProjproddrugManager bidProjproddrugManager;
	
	@Value("#{sysProp['system.province']}")
	private String province;

	/**
	 * @category 进入医疗机构列表页面
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toHospList")
	public String toHospList() {
		DicAreaForm area = dicAreaManager.getDicAreaById(province);
		request.setAttribute("area", area);
		return "/trading/catalog/hospList";
	}

	/**
	 * @category 查询医疗机构列表
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getHospList")
	@ResponseBody
	public Pagination getHospList(SubHospInfo hospInfo) {
		log.info("enter getHospList method");
		Pagination page = new Pagination(request);
		String hospClassifyIds = request.getParameter("hospClassifyIds");
		page.getConditions().put("hospClassifyIds", hospClassifyIds);
		String hospType = request.getParameter("hospType");
		page.getConditions().put("hospType", hospType);
		try {
			String areaId = AreaUtil.getAreaStartCode(province, request.getParameter("area2"), request.getParameter("area3"));   
			hospInfo.setAreaId(areaId);
		    hospCatalogManager.getHospList(hospInfo, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 进入医院商品目录查看（按医疗机构查看）
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toCatalogByHosp")
	public String toCatalogByHosp(Model model, String hospId) {
		HospInfo hospInfo = hospInfoManager.getHospInfoById(hospId);
		model.addAttribute("hospInfo", hospInfo);
		List<DicSys> mlist = DicSysUtil.getDicListByClassCode(Constants.PRO_METHOD);
		request.setAttribute("list", mlist);
		return "/trading/catalog/catalogByHosp";
	}

	/**
	 * @category 查询医院商品目录
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getCatalogByHosp")
	@ResponseBody
	public Pagination getCatalogByHosp(SubGoods goods) {
		log.info("enter getCatalogByHosp method");
		Pagination page = new Pagination(request);
		try {
			hospCatalogManager.getCatalogByHosp(goods, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
/********************wsj医院商品目录查看OPEN*************************/
	/**
	 * @category 卫生局进入医疗机构列表页面（本地区的）
	 * @date 2015年11月13日10:10:52
	 * @return
	 */
	@RequestMapping("/toHospListByWSJ")
	public String toHospListByWSJ() {
		return "/trading/catalog/hospListByWSJ";
	}

	/**
	 * @category 查询医疗机构列表
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getHospListByWSJ")
	@ResponseBody
	public Pagination getHospListByWSJ(SubHospInfo hospInfo) {
		log.info("enter getHospListByWSJ method");
		Pagination page = new Pagination(request);
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			String areaId = hospCatalogManager.getAreaIdByOrgId(user.getOrgId());
			hospInfo.setAreaId(AreaUtil.escapeAreaId(areaId).replace("_", ""));
			hospCatalogManager.getHospList(hospInfo, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
/********************wsj医院商品目录查看CLOSE*************************/
/********************生产企业：医院商品目录查看OPEN*************************/
	/**
	 * @category 查看医疗机构列表页面
	 * @date 2015年11月13日10:10:52
	 * @return
	 */
	@RequestMapping("/toHospListBySC")
	public String toHospListBySC() {
		return "/trading/catalog/hospListBySC";
	}

	/**
	 * @category 获取医疗机构列表数据（生产企业端）
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getHospListBySC")
	@ResponseBody
	public Pagination getHospListBySC(SubHospInfo hospInfo) {
		log.info("enter getHospListBySC method");
		Pagination page = new Pagination(request);
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			StdCompinfo sc = (StdCompinfo)user.getInfo();
			hospInfo.setProdCompCode(sc.getCompCode());
			hospCatalogManager.getHospListBySC(hospInfo, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * @category 进入医院商品目录查看（按医疗机构查看）
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toCatalogByHospSC")
	public String toCatalogByHospSC(Model model, String hospCode) {
		HospInfo hospInfo = (HospInfo) bidProjproddrugManager.getUniquerResult(HospInfo.class, "hospCode", hospCode);
		model.addAttribute("hospInfo", hospInfo);
		return "/trading/catalog/catalogByHospSC";
	}
	
	/**
	 * @category 按商品查看（生产企业端）
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toPurHospcatalogBySC")
	public String toPurHospcatalogBySC(Model model) {
		return "/trading/catalog/purHospcatalogBySC";
	}
	/**
	 * @category 查看有哪些医疗机构在使用该商品（生产企业端）
	 * @date 2015年11月19日20:31:05
	 * @return
	 */
	@RequestMapping("/toHospListByGoogsSC")
	public String toHospListByGoogsSC(Model model,SubGoods goods) {
		try {
			goods.setDrugName(new String(goods.getDrugName().getBytes("iso8859-1"),"utf-8"));
			goods.setFormName(new String(goods.getFormName().getBytes("iso8859-1"),"utf-8")); 
			goods.setSpecName(new String(goods.getSpecName().getBytes("iso8859-1"),"utf-8")); 
			goods.setFactor(new String(goods.getFactor().getBytes("iso8859-1"),"utf-8")); 
			goods.setUnit(new String(goods.getUnit().getBytes("iso8859-1"),"utf-8")); 
			goods.setMaterialName(new String(goods.getMaterialName().getBytes("iso8859-1"),"utf-8")); 
		model.addAttribute("goods", goods);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/trading/catalog/hospListByGoogsSC";
	}
	/**
	 * @category 查询医院商品目录
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getCatalogByHospSC")
	@ResponseBody
	public Pagination getCatalogByHospSC(SubGoods goods) {
		log.info("enter getCatalogByHospSC method");
		Pagination page = new Pagination(request);
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			StdCompinfo sc = (StdCompinfo)user.getInfo();
			goods.setProdCompcode(sc.getCompCode());
			hospCatalogManager.getCatalogByHospSC(goods, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * @category 医疗机构按商品查看
	 * @date 2015年11月18日11:33:16
	 * @return
	 */
	@RequestMapping("/toGoodsCatalogBySC")
	public String toGoodsCatalogBySC(Model model, String hospId) {
		HospInfo hospInfo = hospInfoManager.getHospInfoById(hospId);
		model.addAttribute("hospInfo", hospInfo);
		return "/trading/catalog/catalogByHospSC";
	}
	
	
	
	
	
	
	
	
	
/********************生产企业：医院商品目录查看CLOSE*************************/
	/**
	 * @category 进入商品列表页面(按用户表用户类型判断采购中心和卫生局)
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toGoodsList")
	public String toGoodsList(Model model) {
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		model.addAttribute("userType", user.getType());
		return "/trading/catalog/goodsList";
	}

	/**
	 * @category 查询商品列表
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getGoodsList")
	@ResponseBody
	public Pagination getGoodsList(SubGoods goods) {
		log.info("enter getGoodsList method");
		Pagination page = new Pagination(request);
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			String areaId = hospCatalogManager.getAreaIdByOrgId(user.getOrgId());
			if(StringUtils.isBlank(areaId)){
				areaId = province.replaceAll("0*$", "");
			}else{
				areaId = areaId.replaceAll("0*$", "");
			}
			goods.setAreaId(areaId);
			hospCatalogManager.getGoodsList(goods, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 进入医院商品目录查看（按商品查看）
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/toCatalogByGoods")
	public String toCatalogByGoods(Model model,SubGoods goods) {
		try {
			goods.setDrugName(new String(goods.getDrugName().getBytes("iso8859-1"),"utf-8"));
			goods.setFormName(new String(goods.getFormName().getBytes("iso8859-1"),"utf-8")); 
			goods.setSpecName(new String(goods.getSpecName().getBytes("iso8859-1"),"utf-8")); 
			goods.setFactor(new String(goods.getFactor().getBytes("iso8859-1"),"utf-8")); 
			goods.setUnit(new String(goods.getUnit().getBytes("iso8859-1"),"utf-8")); 
			goods.setMaterialName(new String(goods.getMaterialName().getBytes("iso8859-1"),"utf-8")); 
		model.addAttribute("goods", goods);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if( UserType.zx.getKey() == goods.getUserType()){
			DicAreaForm area = dicAreaManager.getDicAreaById(province);
			request.setAttribute("area", area);
		}
	
		
		return "/trading/catalog/catalogByGoods";
	}

	/**
	 * @category 查询商品下的医疗机构采购目录列表(中心根据商品查看旗下的医疗机构)
	 * @date 2015年7月7日
	 * @return
	 */
	@RequestMapping("/getCatalogByGoods")
	@ResponseBody
	public Pagination getCatalogByGoods(SubHospInfo hospInfo,String area2,String area3) {
		log.info("enter getCatalogByGoods method");
		Pagination page = new Pagination(request);
		try {
			String areaId ="";
			if(hospInfo.getUserType()!=null && hospInfo.getUserType()==UserType.hszx.getKey()){
				SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
				 areaId = hospCatalogManager.getAreaIdByOrgId(user.getOrgId());
				if(StringUtils.isNotBlank(areaId)){
					areaId = areaId.replaceAll("0*$", "");
				}
			}else if(hospInfo.getUserType()!=null && hospInfo.getUserType()==UserType.zx.getKey()){
				areaId = AreaUtil.getAreaStartCode(province, area2, area3);
			}
			hospInfo.setAreaId(areaId);
			hospCatalogManager.getCatalogByGoods(hospInfo, page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * 
	 *@category 中心端批量删除医疗机构目录
	 *@author 邱磊
	 *@date 2015年12月24日 下午2:43:48
	 *@param 
	 *@return Pagination
	 */
	@RequestMapping("/batchDelete")
	@ResponseBody
	public Pagination batchDelete(String array){
		Pagination page = new Pagination();
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				String hospCode = request.getParameter("hospCode");
				hospCatalogManager.batchDelete(list, hospCode);
				page.setSuccess(true);
				page.setMsg("删除成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("删除失败！");
		}
		return page;
	}

}
